const mongoose = require('mongoose')
const bcrypt = require('bcrypt')
const boom = require('boom')
const jwt = require('jsonwebtoken')

const User = require('../models/user')
const e = require('express')

const environment = process.env.NODE_ENV
const stage = require('../config')[environment]

module.exports = {
  login: (req, res, next) => {
    mongoose.connect(process.env.MONGOLAB_URI, stage.mongo_options).then(
      () => {
        let result = {}
        let status = 200
        const {
          username,
          password
        } = req.body
        User.findOne({
          username
        }).
        select('+password').
        exec(function (err, user) {
          if (err) {
            mongoose.connection.close()
            return next(boom.badImplementation(err))
          }
          if (!user) {
            status = 401
            result.status = status
            result.error = `Authentication error`
            mongoose.connection.close()
            return res.status(status).send(result)
          } else {
            bcrypt.compare(password, user.password).then(match => {
              if (match) {
                status = 200
                // Create a token
                const payload = {
                  user: user.username
                }
                const options = {
                  expiresIn: '2d',
                  issuer: 'https://51reader.cn'
                }
                const secret = process.env.JWT_SECRET
                const token = jwt.sign(payload, secret, options)
                let data = {}
                let userInfo = {}
                userInfo._id = user._id
                userInfo.username = user.username
                userInfo.avatar = user.avatar
                data.token = token
                data.user = userInfo
                result.status = status
                result.data = data
              } else {
                status = 401
                result.status = status
                result.error = `Authentication error`
              }
              mongoose.connection.close()
              return res.status(status).send(result)
            }).catch(err => {
              mongoose.connection.close()
              return next(boom.badImplementation(err))
            })
          }
        })
      },
      err => {
        mongoose.connection.close()
        return next(boom.badImplementation(err))
      }
    )
  }
}
